package priv.chenkai.spring_cli.service;

import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import priv.chenkai.spring_cli.client.bo.FileBo;
import priv.chenkai.spring_cli.util.DateTime;

import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * @Author:chenkai
 * @Date: 2018/5/11 9:51
 */
@Service
public class FileUploadService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 上传单个文件
     * @param file 文件字节流
     * @param contentType 文件类型
     * @param rootPath 文件根目录
     * @return
     * @throws IOException
     */
    public String upload(byte[] file,String contentType, String rootPath) throws IOException {
        String filePath = saveFile(file, contentType, rootPath);
        return filePath;
    }

    /**
     * 批量上传文件
     * @param files 文件列表
     * @param rootPath 文件根目录
     * @return
     * @throws IOException
     */
    public List<String> uploads(List<FileBo> files, String rootPath) throws IOException {
        if(files == null || files.isEmpty()){
            return Collections.emptyList();
        }
        List<String> list = Lists.newArrayList();
        for (FileBo bo: files){
            String filePath = saveFile(bo.getContent(), bo.getType(), rootPath);
            list.add(filePath);
        }
        return list;
    }

    private String saveFile(byte[] file,String contentType, String rootPath) throws IOException {
        //生成uuid作为文件名称
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //获得文件类型（可以判断如果不是图片，禁止上传）
        //获得文件后缀名称
        String imageName = contentType.substring(contentType.indexOf("/") + 1);
        //文件目录为：根目录 + 日期 + 文件名
        String filePath = "d://image/" + DateTime.getDate2(System.currentTimeMillis());
        logger.info("上传的文件名为:{}", filePath);
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        filePath = filePath + "/" + uuid + "." + imageName;
        FileOutputStream out = new FileOutputStream(filePath);
        out.write(file);
        out.flush();
        out.close();
        return filePath;
    }
}
